package com.zerocarbon.framework.web.properties;

import cn.hutool.core.collection.CollUtil;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.AntPathMatcher;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Rest配置
 * @author wyf
 */
@Data
@ConfigurationProperties(RestProperties.PREFIX)
public class RestProperties {
	
	public static final String PREFIX = "zerocarbon.rest";
    
    private Valid valid = new Valid();
    
    private Boolean tokenOnlineValid = false;			//验证token是否被踢
    
    private Map<String, String> appSecretMap;			//设置PC应用 appKey、appSecret
    private String appSecretInvoke = "FEIGN";				//查询APP应用信息的调用方式（默认本地FEIGN） FEIGN：FEIGN调用， SERVICE：本地调用
    
    /**
     * 默认不认证地址
     */
    private List<String> defaultIgnoreUrl = CollUtil.newArrayList(
            "/error",
            "/actuator/**",
            "/gate/**",
            "/static/**",
            "/**/swagger-ui.html",
            "/**/doc.html",
            "/**/webjars/**",
            "/**/v2/api-docs/**",
            "/**/v2/api-docs-ext/**",
            "/**/swagger-resources/**",
            "/webjars/**",
            "/druid/**"
    );
    
    /**
     * 设置不用认证的url
     */
    private List<String> ignoreUrls = new ArrayList<>();

    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();
    
    public boolean isIgnoreToken(String path) {
    	if(ignoreUrls.size()==0)
    		return isIgnoreToken(this.getDefaultIgnoreUrl(), path);
    	else {
    		return isIgnoreToken(this.getIgnoreUrls(), path) || isIgnoreToken(this.getDefaultIgnoreUrl(), path);
    	}
    }
    
    private boolean isIgnoreToken(List<String> list, String path) {
    	return list.stream().anyMatch((url) -> path.startsWith(url) || ANT_PATH_MATCHER.match(url, path));
    }
    
    @Setter
    @Getter
    public static class Valid {
    	
    	/**
         * 是否启用验证
         */
        private Boolean enabled = true;
        
        /**
         * Handler执行（IHandler：框架中Handler实现类执行， IService：本地工程的Handler实现类执行）
         */
        private String type = "IHandler";
    }
}
